<!DOCTYPE html>
<html>
<head>
    <title>聊天测试</title>
    <meta charset="utf-8">
</head>
<body>
<div>
    <br><br><br><br><br><br>
    <input type="button" value="用户A 登录请求示例" onclick="login()"/>
    <input type="button" value=" -> B 聊天示例" onclick="chat1()"/>
</div>
<div id="messages"></div>
<script type="text/javascript">
    var webSocket = new WebSocket('ws://192.168.1.43:6789');
    webSocket.onerror = function (event) {
        alert(event.data);
    };
    //与WebSocket建立连接
    // webSocket.onopen = function (event) {
    //     alert("onopen:与WebSocket建立连接了"+event.data);
    //     document.getElementById('messages').innerHTML = '握手成功';
    // };
    //处理服务器返回的信息
    webSocket.onmessage = function (event) {
        alert("onmessage:处理服务器返回的信息开始" + event.data);
        document.getElementById('messages').innerHTML += '<br />' + event.data;
    };

    function login() {
        var login = "{" +
            "\"cmd\":\"5\"," +
            "\"loginname\":\"A\"," +
            "\"password\":\"密码\"," +
            "\"token\":\"2e37b8b3596d476da66d140ea33d1d48\"" +
            "}";
        //向服务器发送请求
        alert("send:向服务器发送请求:" + login);
        webSocket.send(login);
    }

    function chat1() {
        // 1.聊天请求消息结构
// 请求:COMMAND_CHAT_REQ(11)
// 响应:COMMAND_CHAT_RESP(12)
        var time = (new Date()).getTime();
        var chat = "{" +
            "\"from\": \"12\"," +
            "\"to\": \"11\"," +
            "\"cmd\":\"11\"," +
            "\"createTime\":" +time+","+
            "\"msgType\": \"0\"," +
            "\"chatType\":\"2\"," +
            "\"content\": \"用户id=12的zhangsan给用户id=1的wwx发送的聊天内容\"" +
            "}";
        //向服务器发送请求
        alert("send:向服务器发送请求:" + chat);
        webSocket.send(chat);
    }
</script>
</body>
</html>
